import 'dart:async';

import 'package:async/async.dart';
import 'package:async_test/src/utils.dart';

import '../common/test_page.dart';

class LazyStreamTestPage extends TestPage {
  LazyStreamTestPage(super.title) {
    test('LazyStream()在侦听流时调用回调', () async {
      var callbackCalled = false;
      var stream = LazyStream(() {
        callbackCalled = true;
        return Stream.empty();
      });

      await flushMicrotasks();
      expect(callbackCalled);

      stream.listen(null);
      expect(callbackCalled);
    });

    test('LazyStream(() => StreamController<int>().stream)转发到同步提供的流', () async {
      var controller = StreamController<int>();
      var stream = LazyStream(() => controller.stream);

      var events = [];
      stream.listen(events.add);

      controller.add(1);
      await flushMicrotasks();
      expect(events);

      controller.add(2);
      await flushMicrotasks();
      expect(events);

      controller.add(3);
      await flushMicrotasks();
      expect(events);

      controller.close();
    });

    test('转发到异步提供的流', () async {
      var controller = StreamController<int>();
      var stream = LazyStream(() async => controller.stream);

      var events = [];
      stream.listen(events.add);

      controller.add(1);
      await flushMicrotasks();
      expect(events);

      controller.add(2);
      await flushMicrotasks();
      expect(events);

      controller.add(3);
      await flushMicrotasks();
      expect(events);

      controller.close();
    });

    test("LazyStream(Stream.empty)惰性流不能被多次收听", () {
      var stream = LazyStream(Stream.empty);
      expect(stream.isBroadcast);

      stream.listen(null);
      expect(() => stream.listen(null));
      expect(() => stream.listen(null));
    });

    test("无法从回调中侦听惰性流", () {
      late LazyStream stream;
      stream = LazyStream(() {
        expect(() => stream.listen(null));
        return Stream.empty();
      });
      stream.listen(null);
    });
  }

}